#!/usr/bin/env node

const fs = require("fs-extra");
const path = require("path");
const chalk = require("chalk");
const { build } = require("esbuild");

async function buildWithEsbuild() {
  const rootDir = process.cwd();
  const distDir = path.join(rootDir, "dist");

  console.log(chalk.cyan.bold("\n开始构建 TYG CLI (esbuild打包+压缩)...\n"));

  try {
    console.log(chalk.blue("清理构建目录..."));
    if (await fs.pathExists(distDir)) {
      await fs.remove(distDir);
    }
    await fs.ensureDir(distDir);
    await fs.ensureDir(path.join(distDir, "bin"));
    console.log(chalk.green("✅ 清理完成"));

    console.log(chalk.blue("打包主入口文件..."));
    await build({
      entryPoints: [path.join(rootDir, "index.js")],
      bundle: true,
      minify: true,
      platform: "node",
      target: "node14",
      outfile: path.join(distDir, "index.js"),
      external: [
        "commander",
        "inquirer",
        "axios",
        "ora",
        "chalk",
        "fs-extra",
        "simple-git",
        "adm-zip",
      ],
      sourcemap: false,
      logLevel: "silent",
    });
    console.log(chalk.green("✅ 主入口文件打包完成"));

    console.log(chalk.blue(" 打包CLI入口文件..."));
    await build({
      entryPoints: [path.join(rootDir, "bin", "tyg.js")],
      bundle: true,
      minify: true,
      platform: "node",
      target: "node14",
      outfile: path.join(distDir, "bin", "tyg.js"),
      external: [
        "commander",
        "inquirer",
        "axios",
        "ora",
        "chalk",
        "fs-extra",
        "simple-git",
        "adm-zip",
      ],
      sourcemap: false,
      logLevel: "silent",
    });
    console.log(chalk.green("✅ CLI入口文件打包完成"));

    console.log(chalk.blue("复制README文件..."));
    await fs.copy(
      path.join(rootDir, "README.md"),
      path.join(distDir, "README.md")
    );
    console.log(chalk.green("✅ README文件复制完成"));

    console.log(chalk.blue(" 创建package.json..."));
    const packageJson = await fs.readJson(path.join(rootDir, "package.json"));
    const distPackageJson = {
      name: packageJson.name,
      version: packageJson.version,
      description: packageJson.description,
      main: "index.js",
      bin: {
        tyg: "./bin/tyg.js",
      },
      keywords: packageJson.keywords,
      author: packageJson.author,
      license: packageJson.license,
      repository: packageJson.repository,
      bugs: packageJson.bugs,
      homepage: packageJson.homepage,
      dependencies: packageJson.dependencies,
      engines: packageJson.engines,
      preferGlobal: packageJson.preferGlobal,
    };
    await fs.writeJson(path.join(distDir, "package.json"), distPackageJson, {
      spaces: 2,
    });
    console.log(chalk.green("✅ package.json创建完成"));

    console.log(chalk.blue("设置可执行权限..."));
    try {
      await fs.chmod(path.join(distDir, "bin", "tyg.js"), "755");
      console.log(chalk.green("✅ 可执行权限设置完成"));
    } catch (error) {
      console.log(chalk.yellow("⚠ 跳过权限设置 (Windows环境)"));
    }

    console.log(chalk.cyan.bold("\n 构建统计:"));
    const files = await fs.readdir(distDir);
    let totalSize = 0;

    for (const file of files) {
      const filePath = path.join(distDir, file);
      const stat = await fs.stat(filePath);

      if (stat.isDirectory()) {
        console.log(chalk.gray(` ${file}/`));
        const subFiles = await fs.readdir(filePath);
        for (const subFile of subFiles) {
          const subFilePath = path.join(filePath, subFile);
          const subStat = await fs.stat(subFilePath);
          const size = (subStat.size / 1024).toFixed(2);
          totalSize += subStat.size;
          console.log(chalk.gray(`  ${subFile} (${size} KB)`));
        }
      } else {
        const size = (stat.size / 1024).toFixed(2);
        totalSize += stat.size;
        console.log(chalk.gray(`${file} (${size} KB)`));
      }
    }

    console.log(
      chalk.cyan.bold(`\n 总大小: ${(totalSize / 1024).toFixed(2)} KB`)
    );
    console.log(chalk.cyan.bold(` 文件数量: ${files.length}个`));

    console.log(chalk.cyan.bold("\n 构建信息:"));
    console.log(chalk.gray(`构建目录: ${distDir}`));
    console.log(chalk.gray(`构建时间: ${new Date().toLocaleString()}`));
    console.log(chalk.gray(`Node版本: ${process.version}`));
    console.log(chalk.gray(`构建工具: esbuild`));

    console.log(chalk.green.bold("\n 构建完成!"));
    console.log(chalk.cyan("发布命令:"));
    console.log(chalk.yellow("\n⚠ 注意: 源码已打包，不会上传到NPM"));
  } catch (error) {
    console.error(chalk.red.bold("\n 构建失败!"));
    console.error(chalk.red(error.message));
    process.exit(1);
  }
}

if (require.main === module) {
  buildWithEsbuild();
}

module.exports = buildWithEsbuild;
